/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.ybuildingvisitorrl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.facedoor.modular.visitor.entity.Visitor;
import vip.xiaonuo.facedoor.modular.visitor.service.VisitorService;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant;
import vip.xiaonuo.modular.remoteapi.stairs.RemoteStairsConstant.DeviceSyncStatus;
import vip.xiaonuo.modular.sync.DeviceEvent;
import vip.xiaonuo.modular.ybuildingvisitorrl.entity.YBuildingVisitorRl;
import vip.xiaonuo.modular.ybuildingvisitorrl.enums.YBuildingVisitorRlExceptionEnum;
import vip.xiaonuo.modular.ybuildingvisitorrl.mapper.YBuildingVisitorRlMapper;
import vip.xiaonuo.modular.ybuildingvisitorrl.param.YBuildingVisitorRlParam;
import vip.xiaonuo.modular.ybuildingvisitorrl.service.YBuildingVisitorRlService;
import vip.xiaonuo.modular.ydeviceevent.entity.YDeviceEvent;
import vip.xiaonuo.modular.ydeviceevent.mapper.YDeviceEventMapper;
import vip.xiaonuo.modular.yelevatordevice.entity.YElevatorDevice;
import vip.xiaonuo.modular.yelevatordevice.mapper.YElevatorDeviceMapper;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 访客建筑人员表service接口实现类
 *
 * @author 胡鹏达
 * @date 2022-08-29 10:50:53
 */
@Service
public class YBuildingVisitorRlServiceImpl extends ServiceImpl<YBuildingVisitorRlMapper, YBuildingVisitorRl> implements YBuildingVisitorRlService {

    @Resource
    private YBuildingVisitorRlMapper buildingVisitorRlMapper;

    @Resource
    private YElevatorDeviceMapper elevatorDeviceMapper;

    @Resource
    private YDeviceEventMapper deviceEventMapper;

    @Resource
    private VisitorService visitorService;

    @Override
    public PageResult<YBuildingVisitorRl> page(YBuildingVisitorRlParam yBuildingVisitorRlParam) {
        return new PageResult<>(buildingVisitorRlMapper.findPage(PageFactory.defaultPage(), yBuildingVisitorRlParam));
    }

    @Override
    public List<YBuildingVisitorRl> list(YBuildingVisitorRlParam yBuildingVisitorRlParam) {
        return this.list();
    }

    @Override
    public void add(YBuildingVisitorRlParam param) {
        Visitor visitor = visitorService.getById(param.getVisitorId());
        addCheck(param, visitor);
        List<YElevatorDevice> devices = elevatorDeviceMapper.selectList(new LambdaQueryWrapper<YElevatorDevice>().eq(YElevatorDevice::getBuildingId, param.getBuildingId()));
        if (CollectionUtils.isEmpty(devices)) {
            throw new ServiceException(500, "该楼栋不存在设备！");
        }
        for (YElevatorDevice device : devices) {
            YBuildingVisitorRl yBuildingVisitorRl = new YBuildingVisitorRl();
            BeanUtil.copyProperties(param, yBuildingVisitorRl);
            yBuildingVisitorRl.setDeviceId(device.getId());
            // 设置为新增访客中
            yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
            yBuildingVisitorRl.setId(null);
            this.save(yBuildingVisitorRl);
        }

        // tips 以后可能用到 后台和访客机的数据都下发到电梯
//
//        // 小程序录入 不下发电梯
//        if (ObjectUtil.equal(visitor.getSource(),2)){
//            miniAppAdd(param);
//            return;
//        }
//        // 后台和访客机录入 下发电梯
//        backstageAdd(param, visitor);
    }

    private void backstageAdd(YBuildingVisitorRlParam param, Visitor visitor) {
        // 查找楼栋下的所有设备
        List<YElevatorDevice> devices = elevatorDeviceMapper.selectList(new LambdaQueryWrapper<YElevatorDevice>().eq(YElevatorDevice::getBuildingId, param.getBuildingId()));
        if (CollectionUtils.isEmpty(devices)) {
            throw new ServiceException(500, "该楼栋不存在设备！");
        }
        if (StringUtils.isBlank(visitor.getIcCard())){
            throw new ServiceException(500,"访客不存在卡号，不允许下发到电梯！");
        }

        for (YElevatorDevice device : devices) {
            YBuildingVisitorRl yBuildingVisitorRl = new YBuildingVisitorRl();
            BeanUtil.copyProperties(param, yBuildingVisitorRl);
            yBuildingVisitorRl.setDeviceId(device.getId());
            // 设置为新增访客中
            yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.ADD);
            yBuildingVisitorRl.setId(null);
            this.save(yBuildingVisitorRl);

            // 保存事件
            YDeviceEvent deviceEvent = new YDeviceEvent();
            deviceEvent.setDeviceNo(device.getDeviceNo());
            deviceEvent.setStatus(DeviceEvent.NEW);
            deviceEvent.setSysType(2);
            deviceEvent.setCreateDate(new Date());
            deviceEvent.setBody(yBuildingVisitorRl.getId().toString());
            deviceEvent.setType(RemoteStairsConstant.RequestCmd.ADD_PERSON);
            deviceEventMapper.insert(deviceEvent);
        }
    }

//    private void miniAppAdd(YBuildingVisitorRlParam param) {
//        List<YElevatorDevice> devices = elevatorDeviceMapper.selectList(new LambdaQueryWrapper<YElevatorDevice>().eq(YElevatorDevice::getBuildingId, param.getBuildingId()));
//        if (CollectionUtils.isEmpty(devices)) {
//            throw new ServiceException(500, "该楼栋不存在设备！");
//        }
//        for (YElevatorDevice device : devices) {
//            YBuildingVisitorRl yBuildingVisitorRl = new YBuildingVisitorRl();
//            BeanUtil.copyProperties(param, yBuildingVisitorRl);
//            yBuildingVisitorRl.setDeviceId(device.getId());
//            // 设置为新增访客中
//            yBuildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
//            yBuildingVisitorRl.setId(null);
//            this.save(yBuildingVisitorRl);
//        }
//    }

    private void addCheck(YBuildingVisitorRlParam param, Visitor visitor) {
        if (visitor ==null){
            throw new ServiceException(500,"访客不存在");
        }

        List<YBuildingVisitorRl> buildingVisitorRls = this.list(new LambdaQueryWrapper<YBuildingVisitorRl>().eq(YBuildingVisitorRl::getBuildingId, param.getBuildingId()).eq(YBuildingVisitorRl::getVisitorId, param.getVisitorId()));
        if (CollectionUtils.isNotEmpty(buildingVisitorRls)) {
            throw new ServiceException(500, "已经存在该楼栋下设备的关联关系！");
        }
        if (StringUtils.isNotBlank(param.getHandFloor()) && param.getHandFloor().contains("，")) {
            throw new ServiceException(500, "请输入英文逗号！");
        }

        if (StringUtils.isNotBlank(param.getHandFloor()) && param.getHandFloor().split(",").length > 20) {
            throw new ServiceException(500, "最多20个手选楼层！");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(YBuildingVisitorRlParam param) {
        // 强制删除
        if (param.getDelFlag()){
            this.removeById(param.getId());
            return;
        }
        // tips 以后可能用到 后台和访客机的数据都下发到电梯
        YBuildingVisitorRl yBuildingVisitorRl = buildingVisitorRlMapper.selectById(param.getId());
        Long visitorId = param.getVisitorId();
        Visitor visitor = visitorService.getById(visitorId);
        // 小程序访客不下发到电梯里 所以直接删除就行了
        if (ObjectUtil.equal(visitor.getSource(),2)||ObjectUtil.equal(visitor.getSource(),1)){
            this.removeById(param.getId());
            return;
        }
        if (Objects.equals(yBuildingVisitorRl.getDeviceSyncStatus(), DeviceSyncStatus.ADD)) {
            this.removeById(param.getId());
            return;
        }
        // 梯控打印二维码 不下发到电梯
        if (StringUtils.isBlank(visitor.getIcCard())){
            this.removeById(param.getId());
            return;
        }
        if (!Objects.equals(yBuildingVisitorRl.getDeviceSyncStatus(), RemoteStairsConstant.DeviceSyncStatus.SYNC_SUCCESS)) {
            throw new ServiceException(500, "设备未同步完毕! 请稍后再试！");
        }
        yBuildingVisitorRl.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.DELETE);
        this.updateById(yBuildingVisitorRl);

        // 存在任务表
        YElevatorDevice device = elevatorDeviceMapper.selectById(yBuildingVisitorRl.getDeviceId());
        YDeviceEvent deviceEvent = new YDeviceEvent();
        deviceEvent.setDeviceNo(device.getDeviceNo());
        deviceEvent.setType(RemoteStairsConstant.RequestCmd.DELETE_PERSON);
        deviceEvent.setCreateDate(new Date());
        deviceEvent.setBody(param.getVisitorId() + ":" + param.getVisitorId());
        deviceEvent.setStatus(DeviceEvent.NEW);
        deviceEvent.setSysType(2);
        deviceEventMapper.insert(deviceEvent);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(YBuildingVisitorRlParam param) {
        YBuildingVisitorRl buildingVisitorRl = this.queryYBuildingVisitorRl(param);

        if (!Objects.equals(buildingVisitorRl.getDeviceSyncStatus(), RemoteStairsConstant.DeviceSyncStatus.SYNC_SUCCESS)
                && !Objects.equals(buildingVisitorRl.getDeviceSyncStatus(), RemoteStairsConstant.DeviceSyncStatus.SYNC_ERROR)) {
            throw new ServiceException(500, "设备未同步完毕! 请稍后再试！");
        }

        if (StringUtils.isNotBlank(param.getHandFloor()) && param.getHandFloor().contains("，")) {
            throw new ServiceException(500, "请输入英文逗号！");
        }

        if (StringUtils.isNotBlank(param.getHandFloor()) && param.getHandFloor().split(",").length > 20) {
            throw new ServiceException(500, "最多20个手选楼层！");
        }

        Visitor visitor = visitorService.getById(buildingVisitorRl.getVisitorId());
        if (visitor==null){
            throw new ServiceException(500,"访客不存在");
        }


        buildingVisitorRl.setHandFloor(param.getHandFloor());
        buildingVisitorRl.setLiveFloor(param.getLiveFloor());
        buildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
        this.updateById(buildingVisitorRl);
//        Visitor byId = visitorService.getById(buildingVisitorRl.getVisitorId());
        // tips 以后可能用到 后台和访客机的数据都下发到电梯

//        // 小程序访客不下发到电梯里 所以直接修改就行了就行了
//        if (ObjectUtil.equal(byId.getSource(),2)){
//            buildingVisitorRl.setHandFloor(param.getHandFloor());
//            buildingVisitorRl.setLiveFloor(param.getLiveFloor());
//            buildingVisitorRl.setDeviceSyncStatus(DeviceSyncStatus.SYNC_SUCCESS);
//            this.updateById(buildingVisitorRl);
//            return;
//        }
//
//        if (StringUtils.isBlank(visitor.getIcCard())){
//            throw new ServiceException(500,"访客不存在卡号，不允许下发到电梯！");
//        }
//        YDeviceEvent errorEventEntity = deviceEventMapper.selectByBody(buildingVisitorRl.getId().toString());
//        if (errorEventEntity != null) {
//            if (errorEventEntity.getType().equals(RemoteStairsConstant.RequestCmd.UPDATE_PERSON)) {
//                // 人员修改事件
//                YElevatorDevice device = elevatorDeviceMapper.selectById(buildingVisitorRl.getDeviceId());
//                YDeviceEvent deviceEvent = new YDeviceEvent();
//                deviceEvent.setDeviceNo(device.getDeviceNo());
//                deviceEvent.setStatus(DeviceEvent.NEW);
//                deviceEvent.setSysType(2);
//                deviceEvent.setBody(buildingVisitorRl.getId().toString());
//                deviceEvent.setType(RemoteStairsConstant.RequestCmd.UPDATE_PERSON);
//                deviceEventMapper.insert(deviceEvent);
//
//            } else {
//                // 保存事件
//                YElevatorDevice device = elevatorDeviceMapper.selectById(buildingVisitorRl.getDeviceId());
//                YDeviceEvent deviceEvent = new YDeviceEvent();
//                deviceEvent.setDeviceNo(device.getDeviceNo());
//                deviceEvent.setStatus(DeviceEvent.NEW);
//                deviceEvent.setCreateDate(new Date());
//                deviceEvent.setSysType(2);
//                deviceEvent.setBody(buildingVisitorRl.getId().toString());
//                deviceEvent.setType(RemoteStairsConstant.RequestCmd.ADD_PERSON);
//                deviceEventMapper.insert(deviceEvent);
//            }
//        } else {
//            // 人员修改事件
//            YElevatorDevice device = elevatorDeviceMapper.selectById(buildingVisitorRl.getDeviceId());
//            YDeviceEvent deviceEvent = new YDeviceEvent();
//            deviceEvent.setDeviceNo(device.getDeviceNo());
//            deviceEvent.setStatus(DeviceEvent.NEW);
//            deviceEvent.setCreateDate(new Date());
//            deviceEvent.setSysType(2);
//            deviceEvent.setBody(buildingVisitorRl.getId().toString());
//            deviceEvent.setType(RemoteStairsConstant.RequestCmd.UPDATE_PERSON);
//            deviceEventMapper.insert(deviceEvent);
//        }
//
//        buildingVisitorRl.setHandFloor(param.getHandFloor());
//        buildingVisitorRl.setLiveFloor(param.getLiveFloor());
//        buildingVisitorRl.setDeviceSyncStatus(RemoteStairsConstant.DeviceSyncStatus.UPDATE);
//        this.updateById(buildingVisitorRl);
    }

    @Override
    public YBuildingVisitorRl detail(YBuildingVisitorRlParam yBuildingVisitorRlParam) {
        return this.queryYBuildingVisitorRl(yBuildingVisitorRlParam);
    }

    /**
     * 获取访客建筑人员表
     *
     * @author 胡鹏达
     * @date 2022-08-29 10:50:53
     */
    private YBuildingVisitorRl queryYBuildingVisitorRl(YBuildingVisitorRlParam yBuildingVisitorRlParam) {
        YBuildingVisitorRl yBuildingVisitorRl = this.getById(yBuildingVisitorRlParam.getId());
        if (ObjectUtil.isNull(yBuildingVisitorRl)) {
            throw new ServiceException(YBuildingVisitorRlExceptionEnum.NOT_EXIST);
        }
        return yBuildingVisitorRl;
    }
}
